package com.aloda.interceptor;

import cn.hutool.core.util.StrUtil;
import com.aloda.constant.RedisConstant;
import com.aloda.dto.UserSafetyDTO;
import com.aloda.properties.TokenProperties;
import com.aloda.tools.RedisOperateUtils;
import com.aloda.tools.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;


@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private TokenProperties tokenProperties;
    private StringRedisTemplate stringRedisTemplate;
    public RefreshTokenInterceptor(TokenProperties tokenProperties, StringRedisTemplate stringRedisTemplate) {
        this.tokenProperties = tokenProperties;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.取出请求头中的token
        String token = request.getHeader(tokenProperties.getUserTokenName());
        if(StrUtil.isBlankIfStr(token)) {
            return true;
        }
        // 2.基于token去redis中寻找用户
        UserSafetyDTO userSafetyDTO = RedisOperateUtils.getUserInRedis(token, stringRedisTemplate);
        if (userSafetyDTO == null) {
            return true;
        }
        // 3.存在将用户保存
        UserHolder.saveUser(userSafetyDTO);
        // 4.刷新redis有效期
        stringRedisTemplate.expire(RedisConstant.USER_TOKEN_KEY + token, RedisConstant.USER_TOKEN_TIMEOUT, TimeUnit.MINUTES);
        // 5.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
